<template>
  <div class="main_box" style="padding:10px">
    <div class="add_wrap">
      <div class="tit">
        <h2>{{ dataForm.libraryId ? `编辑资讯（id:${dataForm.libraryId}）` : "新增资讯" }}</h2>
        <el-button type="success" plain size="small" icon="fa fa-mail-forward" @click="returnList">返回</el-button>
      </div>
      <el-form :model="dataForm" ref="dataForm" label-width="200px" :rules="roleRules">
        <el-row>
          <el-form-item prop="libraryName" label="资讯名">
            <el-input v-model="dataForm.libraryName"></el-input>
          </el-form-item>

          <el-form-item prop="mainImage" label="资讯主图">
            <upload-img class="upload-img" @uploadFileList="getImgUrl" folder="information">
              <img v-if="dataForm.mainImage" width="100%" :src="dataForm.mainImage" alt="" />
              <div class="tip" v-if="!dataForm.mainImage">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">
                  将图片拖到此处，或<em>点击上传</em>
                </div>
              </div>
            </upload-img>
          </el-form-item>
          <el-form-item prop="firstClassifyId" label="分类名">
            <el-cascader v-model="treeList" :props="propsTree" :options="classTreeList"
              @change="handleChange"></el-cascader>
          </el-form-item>
          <el-form-item prop="tagInfoIds" label="标签">
            <!-- <el-input v-model="dataForm.tagName"></el-input> -->
            <el-select v-model="dataForm.tagInfoIds" multiple placeholder="请先选择分类名">
              <el-option v-for="item in tagList" :key="item.value" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="addressList" label="地址">
            <Address :addressList="addressList" @getAddress="getAddress" :level="3" :isCheckStrictly="true"/>
          </el-form-item>
          <el-form-item label="小区" prop="villageId">
            <el-select v-model="dataForm.villageId" clearable filterable @change="handleVillageChange">
              <el-option v-for="item in villageList" :value="item.id" :label="item.name" :key="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="keywords" label="关键字">
            <el-input v-model="dataForm.keywords"></el-input>
          </el-form-item>

          <el-form-item prop="sort" label="排序">
            <el-input type="number" v-model.number="dataForm.sort"></el-input>
          </el-form-item>

          <el-form-item prop="serverCodes" label="货品库编码">
            <el-input type="textarea" v-model="dataForm.serverCodes"></el-input>
          </el-form-item>

          <el-form-item prop="introduce" label="资讯简介">
            <el-input type="textarea" v-model="dataForm.introduce"></el-input>
          </el-form-item>
          <!--  -->

          <RichEditor :richText="dataForm.content" @getRichText="getRichText"></RichEditor>
        </el-row>

        <el-row>
          <el-form-item>
            <el-button plain type="primary" @click="sureClick">保 存</el-button>
            <el-button plain @click="returnList">取 消</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
import * as message from "@/constants/message";
import TagRuleApi from "@/api/operation/tagModel";
import Address from "@/components/Address";
import RichEditor from "../../components/RichEditor.vue";
import UploadImg from "@/components/UploadImg";
import VillageApi from "@/api/address/village"
import informationRuleApi from "../../api/operation/InformationModel";
export default {
  data() {
    return {
      propsTree: {
        label: "name",
        value: "id"
      },

      dataForm: {
        libraryId: "",
        libraryName: "",
        firstClassifyId: "",
        firstClassifyName: "",
        secondClassifyId: "",
        secondClassifyName: "",
        thirdClassifyId: "",
        thirdClassifyName: "",
        provinceId: "",
        provinceName: "",
        cityId: "",
        cityName: "",
        areaId: "",
        villageId:"",
        villageName:"",
        areaName: "",
        keywords: "",
        tagInfoIds: "",
        sort: "",
        mainImage: "",
        introduce: "",
        content: "",
        serverCodes: '',

      },
      addressList: [],
      departList: [],
      classTreeList: [],
      villageList:[],
      tagList: [],
      treeList: [],
      loadingIns: false,
      roleRules: {
        libraryName: [
          { required: true, message: "请输人资讯名", trigger: "blur" }
        ],
        mainImage: [
          { required: true, message: "请上传资讯主图", trigger: "blur" }
        ],
        /*tagInfoIds: [
          { required: true, message: "请选择标签", trigger: "blur" }
        ],*/
        keywords: [
          { required: true, message: "请输入关键字", trigger: "blur" }
        ],
      }
      // sysDepartList:[],
    };
  },
  components: {
    UploadImg,
    Address,
    RichEditor
  },
  mounted() {
    this.init();
  },
  methods: {
    getRichText(val) {
      this.dataForm.content = val
    },
    getAddress(e) {
      this.dataForm.villageId = ""
      this.dataForm.villageName = ""
      this.villageList=[]
      this.dataForm.provinceId = e.provinceId
      this.dataForm.provinceName = e.provinceName
      this.dataForm.cityId = e.cityId
      this.dataForm.cityName = e.cityName
      this.dataForm.areaId = e.areaId
      this.dataForm.areaName = e.areaName
      if(e.provinceId){
        this.getVillageList()
      }
    },
    async getVillageList(){
      const {provinceId,cityId,areaId} = this.dataForm
      if(!provinceId)return
      const params = {
        provinceId,
        cityId,
        areaId
      }
      const res = await VillageApi.villageList(params)
      this.villageList = res.data
    },
    handleVillageChange(e){
      const {dataForm,villageList} = this
      if(e){
        dataForm.villageName = villageList.find(item=>item.id==e).name
      }else{
        dataForm.villageName=""
      }
    },
    handleChange(e) {
      console.log(e);
      let [firstClassifyId, secondClassifyId, thirdClassifyId] = e;

      let list = this.$Utils.filterTreeToArr(
        this.classTreeList,
        { id: thirdClassifyId || secondClassifyId || firstClassifyId },
        "id"
      );
      let [obj1, obj2, obj3] = list;
      this.dataForm.firstClassifyId = obj1.id || "";
      this.dataForm.firstClassifyName = obj1.name || "";
      this.dataForm.secondClassifyId = obj2.id || "";
      this.dataForm.secondClassifyName = obj2.name || "";
      this.dataForm.thirdClassifyId = obj3.id || "";
      this.dataForm.thirdClassifyName = obj3.name || "";
      this.getTag()
    },
    getTag() {
      informationRuleApi
        .tagInfoList({
          thirdClassifyIds: this.dataForm.thirdClassifyId
        })
        .then(res => {
          //console.log(res);
          this.tagList = res.data
        });
    },
    init() {
      if (this.$route.query.id) {
        this.dataForm.libraryId = this.$route.query.id;
        this.getData();
      }

      TagRuleApi.classifyTree().then(res => {
        this.classTreeList = res.data;
      });
    },
    keydown(e) {
      if (e.keyCode == 32) {
        e.returnValue = false;
      }
    },
    getData() {
      informationRuleApi.libraryInfo({
        id: this.dataForm.libraryId
      }).then(res => {
        this.$Utils.bindingBean(this.dataForm, res.data);

        const data = res.data
        const departIds = []
        data.firstClassifyId ? departIds.push(data.firstClassifyId) : ''
        data.secondClassifyId ? departIds.push(data.secondClassifyId) : ''
        data.thirdClassifyId ? departIds.push(data.thirdClassifyId) : ''
        this.treeList = departIds
        this.getTag()
        this.dataForm.tagInfoIds = data.tagInfos.map(item => item.id)

        const addressArr = []
        data.provinceId ? addressArr.push(data.provinceId) : ''
        data.cityId ? addressArr.push(data.cityId) : ''
        data.areaId ? addressArr.push(data.areaId) : ''
        data.provinceName ? addressArr.push(data.provinceName) : ''
        data.cityName ? addressArr.push(data.cityName) : ''
        data.areaName ? addressArr.push(data.areaName) : ''
        this.addressList = addressArr

        if(data.provinceId){
          this.getVillageList()
        }

      });
    },
    getImgUrl(val) {
      if (val.length > 0) {
        this.dataForm.mainImage = val[0];
      }
    },
    sureClick() {
      const {provinceId,serverCodes,introduce} = this.dataForm
      if(!provinceId){
        this.$message.error("请选择地址")
        return
      }
      this.dataForm.serverCodes = serverCodes.replace(/\s/g,"")
      this.dataForm.introduce = introduce.replace(/\s/g,"")
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          this.$confirm(
            message.MSG_CONFIRM_SAVE_ALTER,
            message.TITLE_PROMPT,
            {}
          ).then(() => {
            if (this.dataForm.libraryId) {
              this.editData();
            } else {
              this.addData();
            }
          });
        }
      });
    },
    addData() {
      informationRuleApi.libraryCrate(this.dataForm).then(res => {
        this.$Utils.notifySuccess();
        this.returnList();
      });
    },
    editData() {
      informationRuleApi.libraryEdit(this.dataForm).then(res => {
        this.$Utils.notifySuccess();
        this.returnList();
      });
    },
    returnList() {
      this.$store.dispatch("delView", this.$route);
      this.$router.push({
        path: "/operation/InformationList"
      });
    }
  }
};
</script>
<style lang="scss" scoped>
@import "@/assets/css/views/add.scss";
</style>
<style lang="scss" scoped>
.upload-img {
  &::v-deep .el-upload {
    width: 100%;

    .el-upload-dragger {
      width: 100%;
      display: flex;
      justify-content: space-around;
      align-items: center;

      .tip {
        padding-bottom: 30px;
      }
    }
  }
}

.preview {
  width: 100%;
  min-height: 300px;
  border: 1px solid black;

  .content {}
}
</style>
